1. Thinking Recursively

And, oh, by the way, I hate having those closing parens jump into existence automatically. Let's turn them off!

In the file ~/.jupyter/custom/custom.js, add these lines:

require(['notebook/js/codecell'], function (codecell) {
        codecell.CodeCell.options_default.cm_config.autoCloseBrackets = false;
        });
In [2]:
%%javascript

IPython.CodeCell.options_default.cm_config.autoCloseBrackets = false;

1.1 Example: member

In [3]:
(define my-member
  (lambda (item lyst)
    (cond
     ((null? lyst) #f)
     ((eq? item (car lyst)) #t)
     (else (my-member item (cdr lyst))))))
In [4]:
(my-member 'a '()) ;; -> #f
Out[4]:
#f
In [5]:
(my-member 'a '(a)) ;; -> #t
Out[5]:
#t
In [6]:
(my-member 'a '(a b c)) ;; -> #t
Out[6]:
#t
In [7]:
(my-member 'c '(a b c)) ;; -> #t
Out[7]:
#t
In [8]:
(my-member 'd '(a b c)) ;; -> #f
Out[8]:
#f
In [9]:
(my-member 'b '(a (b) c)) ;; -> #f
Out[9]:
#f

1.2 Example: length

In [10]:
(define my-length
  (lambda (lyst)
    (cond
     ((null? lyst) 0)
     (#t (+ 1 (my-length (cdr lyst)))))))
In [11]:
(my-length '()) ;; -> 0
Out[11]:
0
In [12]:
(my-length '(100)) ;; -> 1
Out[12]:
1
In [13]:
(my-length '(100 (200) 300)) ;; -> 3
Out[13]:
3

1.3 Example: sum

In [18]:
(define my-sum
  (lambda (lyst)
    (cond
     [(null? lyst) 0]
     [else (+ (car lyst) 
              (my-sum (cdr lyst)))])))
In [19]:
(my-sum '()) ;; -> 0
Out[19]:
0
In [20]:
(my-sum '(23)) ;; -> 23
Out[20]:
23
In [21]:
(my-sum '(1 2 3)) ;; -> 6
Out[21]:
6
In [25]:
(my-sum '(1 2 3 (4 (5) 6) 7))

Traceback (most recent call last):
  File "In [25]", line 1, col 1, in 'my-sum'
  File "In [18]", line 6, col 15, in 'my-sum'
  File "In [18]", line 6, col 15, in 'my-sum'
  File "In [18]", line 6, col 15, in 'my-sum'
  File "In [18]", line 5, col 12, in '+'
UnhandledException: unsupported operand type(s) for +: 'int' and 'cons'

1.4 Example: sum*

In [26]:
(define sum*
  (trace-lambda "sum*" (lyst)
    (cond
     [(null? lyst) 0]
     [(list? (car lyst)) (+ (sum* (car lyst))
                            (sum* (cdr lyst)))]
     [else (+ (car lyst) 
              (sum* (cdr lyst)))])))
In [27]:
(sum* '(1 2 3 (4 (5) 6) 7)) ;; -> 28
call: ("sum*" (1 2 3 (4 (5) 6) 7))
call: ("sum*" (2 3 (4 (5) 6) 7))
call: ("sum*" (3 (4 (5) 6) 7))
call: ("sum*" ((4 (5) 6) 7))
call: ("sum*" (4 (5) 6))
call: ("sum*" ((5) 6))
call: ("sum*" (5))
call: ("sum*" ())
return: 0
return: 5
call: ("sum*" (6))
call: ("sum*" ())
return: 0
return: 6
return: 11
return: 15
call: ("sum*" (7))
call: ("sum*" ())
return: 0
return: 7
return: 22
return: 25
return: 27
return: 28
Out[27]:
28